<?php

namespace Biz\model\activity;
use Doraemon\tools\ImgUrl;

class PageModuleImg extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_activity';

    const _DATABASE_ = 'shop_activity';

    const _TABLE_NAME = 'page_module_img';


    const STATUS_NORMAL = 1;
    const STATUS_DELETE = 9;

    public static function insertModuleImg($data)
    {
        $data['status'] = self::STATUS_NORMAL;
        $data['addtime'] = date("Y-m-d H:i:s");
        if (self::insert($data)->rowcount()) {
            return self::id();
        } else {
            return false;
        }
    }

    public static function addModuleImg($pageId, $moduleId, $imgIds)
    {
        foreach ($imgIds as $imgId) {
            $data = [
                'page_id' => $pageId,
                'module_id' => $moduleId,
                'pic_id' => $imgId,
                'status' => self::STATUS_NORMAL,
                'addtime' => date('Y-m-d H:i:s')
            ];
            self::insert($data);
        }
        return true;
    }

    public static function updateModuleImg($imgId, $data)
    {
        $ret = self::update($data, ['id' => $imgId]);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function saveModuleImgSort($sortInfo)
    {
        foreach ($sortInfo as $imgId => $sort) {
            self::update(['sort' => $sort], ['id' => $imgId]);
        }
    }

    private static function formatImgInfo($imgInfo)
    {
        $imgInfo['img_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $imgInfo['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI);
        return $imgInfo;
    }

    public static function getImgByModuleId($moduleId)
    {
        $imgList= self::select("*",
            [
                'AND' => [
                    'module_id' => $moduleId,
                    'status' => self::STATUS_NORMAL
                ],
                'ORDER' => [
                    'sort',
                    'id'
                ]
            ]);
        if ($imgList) {
            foreach ($imgList as &$img) {
                $img = self::formatImgInfo($img);
            }
        }
        return $imgList;
    }

    public static function chageImgStatusById($id, $status)
    {
        if (self::update(['status' => $status], ["id" => $id])->rowcount()) {
            return $id;
        }
    }
}